#!/usr/bin/perl
#
# patchuser - patch up an user entry that has gone AWOL, based on
# a person entry
#
use POSIX;
use FileTable;
use Validate::Machines;


if ($ARGV[0] eq "-f") {
    $force = 1;
    shift;
} elsif ($ARGV[0] eq "-c") {
    $create = 1;
    shift;
} if ($ARGV[0] =~ /^-/) {
    die "Usage: $0 [-c] [-f] userkey...\n";
}
$users = FileTable::open("db/users", O_RDWR);
$persons = FileTable::open("db/persons");
for $recno (@ARGV) {
    if ($recno =~ /^(\d+)-(\d+)$/) {
	$key = $recno;
	$recno = $1;
    }
    if ($recno !~ /^\d+$/) {
	die "Usage: $0 [-f] recno...\n";
    }
    $person = $persons->get($recno);
    if (!$person) {
	print STDERR "Person $recno not found\n";
        if ($force) {
	    $user = $users->get($recno);
	    if (!$user) {
		print STDERR "No user $recno\n";
		next;
	    } elsif ($user->{person} eq "y") {
		print STDERR "Removing person reference\n";
		delete $user->{person};
		$user->store;
	    }
	} elsif ($create) {
	    $user = $users->get($recno);
	    if ($user) {
		print STDERR "User $recno already exists\n";
	    } elsif (!$key) {
		print STDERR "Cannot create $recno - no key\n";
	    } else {
		$user = $users->get($recno, O_CREAT);
		$user->{key} = $key;
		$user->store;
	    }
	    next;
	}
	next;
    }
    $user = $users->get($recno, O_CREAT);
    if ($user->{person} && !$force) {
	print STDERR "User $recno existed and had person = ",
	      $user->{person}, "\n";
	if ($user->{key}) {
	    print STDERR "Key is $user->{key}\n";
	    next;
	} elsif ($key) {
	    print STDERR "Setting key to $key\n";
	    $user->{key} = $key;
	    $user->store;
	    next;
	} else {
	    next;
	}
    }
    $user->{person} = "y";
    $user->{recdate} = $person->{recdate};
    $user->{email} = $person->{email};
    $user->{key} = $key if $key;
    print "Updating $recno\n";
    $user->store;
}
